package com.mmp.common.util;

import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import com.mmp.common.bo.JRBean;

public class JasperUtil {

	public static void exportReportToResponseOutputStreamAsPDF(JRBean b, HttpServletResponse response) throws Exception {
		// Setting up virtualizer to have only 3 pages in memory

		// JRFileVirtualizer virtualizer = new JRFileVirtualizer(3,
		// System.getProperty("java.io.tmpdir"));

		// Map<String, Object> parameters = new HashMap<String, Object>();
		// JRPropertiesUtil.loadProperties("jasperreports.properties", null);
		// parameters.put(JRPdfExporterParameter.PROPERTY_CHARACTER_ENCODING,
		// "utf-8");
		// parameters.putAll(b.getParams());

		// String path = getServletContext().getRealPath("/WEB-INF/");

		OutputStream os = null;
		// JasperPrint jp =
		// JRLoader.loadJasperPrintFromFile(b.getJasperPrintPath(), null);

		JasperPrint jasperPrint = null;
		if (b.getDataSource() != null)
			jasperPrint = JasperFillManager.fillReport(b.getJasperPrintPath(), b.getParams(), b.getDataSource());
		else
			jasperPrint = JasperFillManager.fillReport(b.getJasperPrintPath(), b.getParams(), b.getDBConnection());

		// jasperPrint.setProperty("language", "java");

		// JRPdfExporter exporter = new JRPdfExporter();
		// exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		byte[] byteStream = JasperExportManager.exportReportToPdf(jasperPrint);

		// JasperExportManager.exportReportToPdfStream(jasperPrint, os);
		// os.flush();

		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition", "inline; filename=\"" + b.getDisplayName() + "\"");
		response.setContentLength(byteStream.length);

		os = response.getOutputStream();
		os.write(byteStream);
		// os.flush();
		// Common.log("" + byteStream.length);
		// int bufSize = Default.RESPONSE_OUTPUT_STREAM_BUFFER_SIZE;
		// int startIndex = -bufSize, endIndex = -1;
		// while ((startIndex += bufSize) < byteStream.length) {
		// endIndex = ((endIndex += bufSize) > byteStream.length - 1) ?
		// byteStream.length - 1 : endIndex;
		// Common.log("" + startIndex);
		// Common.log("" + endIndex);
		// os.write(Arrays.copyOfRange(byteStream, startIndex, endIndex));
		// os.flush();
		// }

		os.close();

	}
}
